#include <QtDeclarative>
#include <QLabel>
#include "plurkclient.h"

#define CONSUMER_KEY "B2lxkOMDnfCH"
#define CONSUMER_SECRET "uu0yrNkFTIa98QJnZMLt5qdWLrsqjvM5"

PlurkClient::PlurkClient(QWidget *parent) :
    QmlApplicationViewer(parent), authView(this), plurkInitDone(false)
{
  settings = PlurkSettings::instance();

  plurkAPI.setConsumerKey(CONSUMER_KEY);
  plurkAPI.setConsumerSecret(CONSUMER_SECRET);

  updateAppKey();

  connect(&plurkAPI, SIGNAL(openAuthUrl(const QUrl &)),
          this, SLOT(openAuthUrl(const QUrl &)));

  connect(&plurkAPI, SIGNAL(finishOAuth()),
          this, SLOT(finishOAuth()));

  connect(&plurkAPI, SIGNAL(plurkRequestError()),
          this, SLOT(plurkRequestError()));

//  connect(&plurkAPI, SIGNAL(appNetworkError()),
//          this, SLOT(appNetworkError()));

  connect(&authView, SIGNAL(authDone(bool, const QString &)),
          this, SLOT(authDone(bool, const QString &)));

  connect(this, SIGNAL(oauthKeys(const QString&, const QString&)),
          settings, SLOT(storeOAuthKeys(const QString&, const QString &)));

  rootContext()->setContextProperty("plurkState", "loading");
  rootContext()->setContextProperty("plurk", &plurkAPI);
  setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
#if defined(MEEGO_EDITION_HARMATTAN)
  setMainQmlFile(QLatin1String("qml/plurker/Harmattan.qml"));
#else
  setMainQmlFile(QLatin1String("qml/plurker/Plurk.qml"));
#endif

#ifdef Q_OS_LINUX
//  setGeometry(0, 0, 854, 480);
#endif

  authView.setVisible(false);
}

void PlurkClient::updateAppKey()
{
  QVariant appKey    = settings->oauthAppKey();
  QVariant appSecret = settings->oauthAppSecret();

  if (appKey.isValid() && appSecret.isValid()) {
    plurkAPI.setAppKey(appKey.toString());
    plurkAPI.setAppSecret(appSecret.toString());
  }
}

void PlurkClient::initRequest()
{
  plurkAPI.initRequestToken();
}

void PlurkClient::openAuthUrl(const QUrl &url)
{
  authView.setVisible(false);
  authView.openAuth(url);
#ifdef Q_OS_LINUX
  authView.setGeometry(0, 0, 854, 480);
#else
  authView.setGeometry(geometry());
#endif
}

void PlurkClient::authDone(bool success, const QString &verifier)
{
  authView.setVisible(false);
  plurkAPI.startAccessToken(verifier);
}

void PlurkClient::finishOAuth()
{
  emit oauthKeys(plurkAPI.appKey(), plurkAPI.appSecret());
  authView.setVisible(false);
  rootContext()->setContextProperty("plurkState", "finishOAuth");
}

void PlurkClient::plurkRequestError()
{
  initRequest();
}
